package everydayGrade.t0;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Author: Siantar
 * @Date: 2023-12-06-20:30
 * @Description: 1.0
 */
public class T2646 {
    public int minimumTotalPrice(int n, int[][] edges, int[] price, int[][] trips) {
        List<Integer>[] mp = new List[n];
        Arrays.setAll(mp, e -> new ArrayList<Integer>());
        for (int[] e : edges) {
            int from = e[0], to = e[1];
            mp[from].add(to);
            mp[to].add(from);
        }
        int[] cnt = new int[n];
        for (int[] trip : trips) {
            int from = trip[0], to = trip[1];
            dfs(from, -1, to, mp, cnt);
        }
        int[] res = dp(0, -1, mp, cnt, price);
        return Math.min(res[0], res[1]);

    }

    public boolean dfs(int p, int pre, int end, List<Integer>[] mp, int[] cnt) {
        if (p == end) {
            cnt[p]++;
            return true;
        }
        for (int next : mp[p]) {
            if (next != pre && dfs(next, p, end, mp, cnt)) {
                cnt[p]++;
                return true;
            }
        }
        return false;
    }

    public int[] dp(int p, int pre, List<Integer>[] mp, int[] cnt, int[] price) {
        int original = price[p] * cnt[p];
        int half = original / 2;
        for (int next : mp[p]) {
            if (next != pre) {
                int[] nextDp = dp(next, p, mp, cnt, price);
                original += Math.min(nextDp[0], nextDp[1]);
                half += nextDp[0];
            }
        }
        return new int[]{original, half};
    }
}
